package com.os.osframe.scaffold.service.impl;

import com.os.osframe.scaffold.domain.ScaffoldXmlTable;
import com.os.osframe.scaffold.domain.ScaffoldXmlTables;
import com.os.osframe.scaffold.service.IConfigTableService;
import com.os.osframe.scaffold.util.FileToZipUtil;
import com.os.osframe.scaffold.util.JaxbUtil;
import com.os.osframe.scaffold.util.PropertyConfigurerLoader;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

/**
 * Created by wangchun on 16/7/7.
 */

@Repository("configTableService")
public class ConfigTableServiceImpl implements IConfigTableService {
    protected static Map<String,ScaffoldXmlTables> tableMap;
    @Resource
    protected PropertyConfigurerLoader propertyConfigurer;

    /**
     * 获取模块列表
     */
    public List<ScaffoldXmlTable> getTableList(String module){

        loadTables(module);
        if(tableMap==null ){
            tableMap= new HashMap();
        }
        if(tableMap.containsKey(module)){
            ScaffoldXmlTables tables=tableMap.get(module);
            if(tables==null){
                tables=new ScaffoldXmlTables();
            }
            if(tables.getScaffoldXmlTableList()==null){
                tables.setScaffoldXmlTableList(new ArrayList());
            }
            return tables.getScaffoldXmlTableList();
        }
        return null;
    }

    /**
     * 获取module对象
     * @param tableName
     * @return
     */
    public ScaffoldXmlTable findTableName(String module,String tableName){
        if(tableName==null || "".equals(tableName.trim())){
            return null;
        }
        List<ScaffoldXmlTable> list=this.getTableList(module);
        if(list==null || list.isEmpty()){
            return null;
        }
        for(ScaffoldXmlTable table:list){
            if(tableName.trim().equals(table.getTableName())){
                return table;
            }
        }
        return null;
    }

    /**
     * 初始化加载配置信息
     */
    public void loadTables(String module) {
        try {
            if(tableMap==null || !tableMap.containsKey(module) ){
                String basePath = (String) propertyConfigurer.getProperty("osframe.file.path");//获取属性配置的服务器路径
                if (basePath.substring(basePath.length() - 1).equals("/")) {
                    basePath = basePath.substring(basePath.length() - 1);
                }
                String modulePath = basePath + "/auto/config/tables/"+module+".xml";
                Document document = null;
                File file = new File(modulePath);
                if(file.exists()){//当文件存在时加载进来
                    SAXReader saxReader = new SAXReader();// 用来读取xml文档
                    document = saxReader.read(file);// 读取xml文档
                    String xml = document.asXML();
                    System.out.println(xml);
                    if(tableMap==null){
                        tableMap=new HashMap<String, ScaffoldXmlTables>();
                    }
                    tableMap.put(module, JaxbUtil.converyToJavaBean(xml, ScaffoldXmlTables.class));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 保存模块配置
     * @param xmlTable
     */
    public void saveTable(String module,ScaffoldXmlTable xmlTable){
        List<ScaffoldXmlTable>  list=this.getTableList(module);

        if(list!=null){
            Boolean bool=true;
            for(int i=0,len=list.size();i<len;i++){
                ScaffoldXmlTable table=list.get(i);
                if(xmlTable.getTableName().trim().equals(table.getTableName())){
                    bool=false;
                    list.remove(i);
                    list.add(i,xmlTable);
                }
            }
            if(bool){
                list.add(xmlTable);
            }

        }else{
            list=new ArrayList<ScaffoldXmlTable>();
            list.add(xmlTable);
            ScaffoldXmlTables tables=new ScaffoldXmlTables();
            tables.setScaffoldXmlTableList(list);
            tableMap.put(module,tables);
        }
        //刷新xml文件
        saveXmlConfig(module);
    }

    /**
     * 删除表的配置
     * @param tableName
     */
    public String delTable(String module,String tableName){
        List<ScaffoldXmlTable>  list=this.getTableList(module);

        if(list!=null){
            Boolean bool=false;
            for(int i=0,len=list.size();i<len;i++){
                ScaffoldXmlTable table=list.get(i);
                if(tableName.trim().equals(table.getTableName())){
                    bool=true;
                    list.remove(i);
                }
            }
            if(bool){
                //刷新xml文件
                saveXmlConfig(module);
                return "0";
            }
        }
        return "1";
    }
    /**
     * 获取字段列表
     * @param module
     * @param tableName
     * @return
     */
    public List getFieldsList(String module,String tableName){
        ScaffoldXmlTable scaffoldXmlTable=this.findTableName(module,tableName);
        if(scaffoldXmlTable!=null){
            return scaffoldXmlTable.getScaffoldXmlFieldList();
        }
        return null;
    }
    /**
     * 保存xml配置
     */
    public void saveXmlConfig(String module){
        try {
            if(!tableMap.containsKey(module)){
                return;
            }
            String basePath = (String) propertyConfigurer.getProperty("osframe.file.path");//获取属性配置的服务器路径
            if (basePath.substring(basePath.length() - 1).equals("/")) {
                basePath = basePath.substring(basePath.length() - 1);
            }
            String modulePath = basePath + "/auto/config/tables/"+module+".xml";
            Document document = null;
            File file = new File(modulePath);
            ScaffoldXmlTables tables=tableMap.get(module);
            String xml = JaxbUtil.convertToXml(tables, "UTF-8");
            BufferedWriter output = null;
            String moduleFolderPath=basePath + "/auto/config/tables";
            File moduleFolder = new File(moduleFolderPath);
            if(!moduleFolder.exists()){
                moduleFolder.mkdirs();
            }
            file.createNewFile();//每次保存都采用覆盖方式
            output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            output.write(xml);
            output.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 代码打包
     * @param module
     * @return
     */
    public Boolean moduleZip(String module){
        String basePath = (String) propertyConfigurer.getProperty("osframe.file.path");//获取属性配置的服务器路径
        if (basePath.substring(basePath.length() - 1).equals("/")) {
            basePath = basePath.substring(basePath.length() - 1);
        }
        String sourcePath=basePath+"/auto/code/"+module.replaceAll("\\.", "/");
        String targetPath=basePath+"/auto/downloads";
        File sourceFile=new File(sourcePath);
        if(!sourceFile.exists()){//当目录不存在时，说明代码没有被生成
            return false;
        }
        String zipBaseFolder=module.replaceAll("\\.", "/");
        //去除最后一级的路径
        if(zipBaseFolder.indexOf("/")>-1){
            zipBaseFolder=zipBaseFolder.substring(0,zipBaseFolder.indexOf("/"))+"/";
        }else{
            zipBaseFolder="";
        }
        FileToZipUtil.fileToZip(sourcePath,targetPath,module,zipBaseFolder);
        return true;
    }
}
